import { debounce } from 'lodash';

let loading: any = null;
let RequestCount = 0;
export function startLoading() {
  if (RequestCount === 0 && !loading) {
    loading = uni.showLoading({
      title: '加载中'
    });
  }
  RequestCount++;
}

export function endLoading() {
  RequestCount--;
  if (RequestCount < 0) RequestCount = 0;
  if (RequestCount === 0) {
    toHideLoading();
  }
}

// 防抖：将 500ms 间隔内的关闭 loading 便合并为一次。防止连续请求时， loading闪烁的问题。
const toHideLoading = debounce(function () {
  if (loading && RequestCount === 0) {
    uni.hideLoading();
    loading = null;
  }
}, 500);
